import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { localGet } from '@/utils/mylocal.js'
import { apiGetUser } from '@/api/use.js'
// 导入组件
const Login = () => import('../views/login/login.vue')
const Home = () => import('../views/home/home.vue')
const Index = () => import('../views/home/index/index.vue')
const My = () => import('../views/home/my/my.vue')
const Chat = () => import('../views/home/my/chat.vue')
const Search = () => import('../views/home/search/search.vue')
const SearchResult = () => import('../views/searchResult/searchResult.vue')
const Detail = () => import('../views/detail/detail.vue')
const Info = () => import('../views/info/info.vue')
const Video = () => import('../views/video/video.vue')

Vue.use(VueRouter)

const routes = [
  // 登录路由:登录成功之后，应该跳转到我的页面
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  // 验证登录路由:登录成功之后，返回到上一个页面
  { path: '/checkLogin', component: Login },
  // 注册 home 路由
  {
    path: '/home',
    component: Home,
    redirect: '/my',

    children: [
      { path: '/index', component: Index }, // 主页路由
      {
        path: '/my',
        component: My, // 需要登录
        meta: {
          needLogin: true
        }
      }, // 我的路由
      { path: '/search', component: Search }, // 搜索路由
      { path: '/video', component: Video } // 搜索路由
    ]
  },
  { path: '/searchResult/:key', component: SearchResult },
  // 文章详情
  { path: '/detail/:artid', component: Detail },
  {
    path: '/info',
    component: Info,
    // 需要登录
    meta: {
      needLogin: true
    }
  },
  { path: '/chat', component: Chat }
]

const router = new VueRouter({
  routes
})

// 前置守卫 (还没有进入想进到的路由)
router.beforeEach(async (to, from, next) => {
  from.meta.top =
    document.documentElement.scrollTop ||
    document.body.scrollTop ||
    window.pageYOffset
  if (store.state.isLogin) {
    next()
  } else if (to.meta.needLogin && !localGet('token')) {
    // 要登录,但未登录,如果没有token跳转到登录
    router.push('/login?next=' + to.fullPath)
  } else {
    // 不需要登录 有token // 不需要登录 没有token // 需要登录有token 有token
    // 如果需要登录,并且当前是已登录状态,直接跳转
    next()
    if (localGet('token')) {
      const res = await apiGetUser(!to.meta.needLogin)
      store.commit('setUserInfo', res.data.data)
      store.commit('setIsLogin', true)
    }
  }
})
// 后置守卫 (已进入想进到的路由)
router.afterEach((to, from) => {
  // to:去哪里的路由信息
  // from :从哪来的路由信息
  window.scrollTo(0, 0)
  console.log('xxxxx')
})
const originalReplace = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  window.scrollTo(0, 0)
  return originalReplace.call(this, location).catch(err => err)
}

export default router
